package wotd.esv;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.logging.Logger;

import wotd.BibleQuery;

public class EsvQuery implements BibleQuery {
	private static final Logger LOG = Logger.getLogger(EsvQuery.class.getName());
	
	@Override
	public String query(String passage) throws IOException {
		LOG.info("Fetching " + passage);
		
		passage = URLEncoder.encode(passage, "UTF-8");
		URL url = new URL("http://www.esvapi.org/v2/rest/passageQuery?include-footnotes&include-short-copyright=false&include-headings=false&include-subheadings=false&include-selahs=false&key=IP&passage=" + passage);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		
		int status = con.getResponseCode();
		String body = read(con.getInputStream());
		
		if (status != 200) {
			throw new IOException("Unable to retrieve passage");
		}
		
		LOG.fine("Retrieved passage " + passage + ": " + body);
		return body;
	}
	
	private String read(InputStream is) throws IOException {
		is = new BufferedInputStream(is);
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];

			int len;
			while ((len = is.read(buf)) != -1) {
				out.write(buf, 0, len);
			}
			return new String(out.toByteArray());
		} finally {
			is.close();
		}
	}
	
	public static void main(String[] args) throws IOException {
		String verse = new EsvQuery().query("John+1:1-4");
		LOG.info(verse);
	}
}
